/**
 * HistoryFileItemServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.jackysoft.data.SortInfo;
import org.jackysoft.entity.FileItem;
import org.jackysoft.entity.HistoryFileItem;
import org.jackysoft.entity.User;
import org.jackysoft.file.FileAdapter;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.FileDataService;
import org.jackysoft.service.HistoryFileItemService;
import org.jackysoft.util.FileInfo;
import org.jackysoft.util.IOUtils;
import org.jackysoft.util.OperationType;
import org.jackysoft.util.SOAOfficeUtil;
import org.jackysoft.util.SpringSecurityUtils;
import org.joda.time.DateTime;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class HistoryFileItemServiceImpl extends AbstractStringIdServiceImpl<HistoryFileItem>
implements HistoryFileItemService{
    /**
	 * 
	 */
	private static final long serialVersionUID = 5139538047478887681L;
	final static Log logger = LogFactory.getLog(HistoryFileItemServiceImpl.class);

	private FileDataService fileService;
	public HistoryFileItemServiceImpl(){
	    this.type = HistoryFileItem.class;
	}

	@Override
	public void save(String fromId) throws DataAccessException, IOException {
		byte[] fileData = SOAOfficeUtil.parseSOAOfficeStream();		
		FileItem file = fileService.getForEdit(fromId);
		User owner = SpringSecurityUtils.getCurrentUser();
	    save(fileData,file.getTitle(),owner,file.getId(),file.getFileType());
	    
	}

	public void save(byte[] fileData,String title,User owner,String originId,String fileType) throws DataAccessException{
		 	FileInfo fi = null;
			try {
				fi = new FileAdapter(fileData, title,owner,getConfig().getDiskBase()).save();
			} catch (IOException e) {
				log.error(e.toString());
			}
		    HistoryFileItem hf = new HistoryFileItem();		
		    hf.setOriginId(originId);
		    hf.setTitle(title);
		    hf.setCreateTime(DateTime.now());
		    hf.setOwner(owner);
		    hf.setDiskBase(getConfig().getDiskBase());
		    hf.setFileType(fileType);
		    hf.setRealName(fi.getRealPath());
		    hf.setImgpath("images/fileico/" + fileType + ".jpg");
		    super.create(hf);
		    logger.info(String.format("用户%s保存了文件 %s",owner.getUsername(),title));
	}
	
	@Override
	@Transactional(readOnly=true)
	public HistoryFileItem openHistoryDoc(String id)throws DataAccessException {
		HistoryFileItem hf = get(id);
		String realName = String.format("%s:%sfiles%s%s", hf.getDiskBase(),File.separator,File.separator,hf.getRealName());
		byte[] content = IOUtils.toByteArray(new File(realName));
		hf.setData(content);
		return hf;
	}

	
	
	
	
	@Override
	protected int listDataSize(SortInfo sortInfo, Map<String, Object> smap) {
		String owner = SpringSecurityUtils.getCurrentUserName();
		String hql = 
				String.format(
				"select count(*) from %s ht where ht.owner.username='%s' order by ht.createTime desc"
				,table(),owner
				);
		Object obj = query(hql).iterate().next();
		return Integer.parseInt(obj.toString());
	}

	@Override
	protected List<HistoryFileItem> listData(int start, int size,
			boolean listAll, SortInfo sortInfo, Map<String, Object> smap) {
		String owner = SpringSecurityUtils.getCurrentUserName();
		String hql = 
				String.format(
				"select new HistoryFileItem(id,title,fileType, createTime,owner) from %s ht where ht.owner.username='%s' order by ht.createTime desc"
				,table(),owner
				);
		List list = query(hql).setFirstResult(start).setMaxResults(size).list();
		return list;
	}

	@Resource
	public void setFileService(FileDataService fileService) {
		this.fileService = fileService;
	}

	@Override
	public FileInfo download(String id) throws Exception {
		Session sess = getSession();
	    String hql = String.format("select new org.jackysoft.entity.FileItem(r.title,r.diskBase,r.realName,r.fileType) from %s  r where r.id='%s'",table(),id);
		List list = sess.createQuery(hql).list();
		FileItem fileItem =(FileItem) list.get(0);				
		String realName = String.format("%s:%sfiles%s%s", fileItem.getDiskBase(),File.separator,File.separator,fileItem.getRealName());
		byte[] bs = IOUtils.toByteArray(new File(realName));

		User user = SpringSecurityUtils.getCurrentUser();
		String opr = "下载";
		OperationType logType = OperationType.System;
		String details = ("用户 " + user.getLocalName() + "["	+ user.getUsername() + "] " + opr + id);
		traceLog(logType, opr, details);
		return new FileInfo(fileItem.getTitle(),fileItem.getRealName(),fileItem.getFileType(),bs);        
		
	}
		
}